package com.zy.pool.pool;

import com.zy.pool.domain.DBbean;

import java.util.*;
import java.sql.*;
/**
 * class_name: ConnectionPoolManager
 * package: com.zy.pool.pool
 * describe: TODO 连接管理类
 * creat_user: Angle
 * creat_date:
 * creat_time:
 **/
public class ConnectionPoolManager{

    /**
     * 连接池存放容器
     */
    public Hashtable<String,IConnectionPool> pools=new Hashtable<>(16);


    private ConnectionPoolManager(){
        super();
        init();
    }

    public static ConnectionPoolManager getInstance(){
        return Singtonle.poolManager;
    }

    private static class Singtonle{
        private static ConnectionPoolManager poolManager=new ConnectionPoolManager();
    }

    /**
     * 初始化所有连接
     */
    public void init(){
        AbstractDBInitInfo dbInitInfo=new DBInfoImpl();
        DBbean dbbean = dbInitInfo.loadProperty();
        IConnectionPool pool = new ConnectionPoolImpl(dbbean);
        if(pool != null){
            pools.put(dbbean.getPoolName(), pool);
            System.out.println("Info:Init connection successed ->" +dbbean.getPoolName());
        }
    }

    /**
     * 获取连接，根据连接池名字获得连接
     */
    public Connection getConenection(String poolName){
        if(poolName==null||"".equals(poolName.trim())){
            poolName="DefaultConnectionPool";
        }
        if(!pools.isEmpty()&&pools.contains(poolName)){
            IConnectionPool ConnectionPool = pools.get(poolName);
            return  ConnectionPool.getConnection();
        }else{
            System.err.println("Error:Can't find this connecion pool ->"+poolName);
            return null;
        }
    }

    /**
     * 关闭,回收连接
     */
    public void close(String poolName,Connection conn){
        if(!pools.isEmpty()&&pools.contains(poolName)){
            IConnectionPool ConnectionPool = getPool(poolName);
            try {
                ConnectionPool.releaseConn(conn);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    // 清空连接池
    public void destroy(String poolName){
        IConnectionPool pool = getPool(poolName);
        if(pool != null){
            pool.destroy();
        }
    }

    // 获得连接池
    public IConnectionPool getPool(String poolName){
        IConnectionPool pool = null;
        if(pools.size() > 0){
            pool = pools.get(poolName);
        }
        return pool;
    }
}